package com.weiweiqin.controller.wechat;


import com.weiweiqin.constants.PropertyConfig;
import com.weiweiqin.controller.home.FOrderController;
import com.weiweiqin.model.Customer;
import com.weiweiqin.service.CustomerService;
import com.weiweiqin.utils.UrlUtil;
import com.weiweiqin.vo.common.Result;
import com.weiweiqin.weixin.util.SignUtil;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping(value = "/weixin")
public class WeiXinLogin {
    private static final Logger logger = LoggerFactory
            .getLogger(FOrderController.class);
    @Autowired
    private CustomerService customerService;
    private static  String APPID = "";
    private static  String XCX_APPID = "wx1e52b3dc0246fd66";
    private static  String XCX_SECRET = "3ef77392a19b35af3de0a940c55aeb5a";
    private static  String SECRET = "";
    private static  String URL = "";
    static {
        APPID =	PropertyConfig.getInstance().getProperty("APPID");
        SECRET = PropertyConfig.getInstance().getProperty("SECRET");
        URL = PropertyConfig.getInstance().getProperty("URL");
    }
    //请求校验（确认请求来自微信服务器）
    @RequestMapping(value = "/doGet",method = RequestMethod.GET)
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 微信加密签名
        String signature 	= request.getParameter("signature");
        // 时间戳
        String timestamp 	= request.getParameter("timestamp");
        // 随机数
        String nonce 		= request.getParameter("nonce");
        // 随机字符串
        String echostr 		= request.getParameter("echostr");
        //通过调用PrintWriter类的print()方法将处理结果respXml返回给微信服务器
        PrintWriter out = null;
        out = response.getWriter();
        // 请求校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            out.print(echostr);
        }
        out.close();
        out = null;
    }

    //请求校验与处理
    @RequestMapping(value = "/doGet",method = RequestMethod.POST)
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
    }

    /**
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, HttpSession session){

        Object customer = session.getAttribute("customer");
        if(null == customer) {
            String url  = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+APPID+"&redirect_uri="+
                    URL+"/loginAuth"+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
            return "redirect:"+url;
        }else {
            return "redirect:"+URL+"?vt"+new Date().getTime()+"#/index?auth=1";
        }

    }


    private String getUserWXLoginInfo(String wxCode) {
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String,String> requestUrlParam = new HashMap<String,String>();
        requestUrlParam.put("appid", XCX_APPID);	//开发者设置中的appId
        requestUrlParam.put("secret", XCX_SECRET);	//开发者设置中的appSecret
        requestUrlParam.put("js_code", wxCode);	//小程序调用wx.login返回的code
        requestUrlParam.put("grant_type", "authorization_code");	//默认参数
        //发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session 接口获取openid用户唯一标识
        String result = UrlUtil.sendPost(requestUrl, requestUrlParam);
        return result;
    }

    /**
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/xcxlogin")
    @ResponseBody
    public String xcxlogin(HttpServletRequest request, HttpServletResponse response, HttpSession session,String code,String nickName,String avatarUrl,String country,String province,String city,int gender){
        logger.info("Enter method wxclogin code="+code);
        //请求微信api获取用户的openid和sessionKey
        Result result = new Result();
        String wxresult  = getUserWXLoginInfo(code);
        JSONObject jsonObject = JSONObject.fromObject(wxresult);
        String openId = jsonObject.getString("openid");
        logger.info("---------------------------------openid="+openId);
        if (StringUtils.isEmpty(openId)) {
            result.setResult(false);
            return result.toJson();
        }
        result.setResult(true);
        Customer cus = customerService.getByOpenid(openId);
        if(null == cus) {
            cus = new Customer();
            cus.setAmount(new BigDecimal(0));
            cus.setIntegral(0);
            cus.setOpenid(openId);
            cus.setNickname(nickName);
            cus.setHeadurl(avatarUrl);
            cus.setCountry(country);
            cus.setProvince(province);
            cus.setCity(city);
            cus.setSex(gender);
            cus.setRegDate(new Date());
            try {
                customerService.save(cus,"");
            }catch (Exception e) {
                logger.info(e.getMessage());
            }
        } else {
            if (StringUtils.isEmpty(cus.getNickname())) {
                cus.setNickname(nickName);
                cus.setHeadurl(avatarUrl);
                cus.setCountry(country);
                cus.setProvince(province);
                cus.setCity(city);
                cus.setSex(gender);
                customerService.update(cus);
            }
        }
        result.setObj(cus.getId());
        return result.toJson();
//        String wxresult  = getUserWXLoginInfo(code);
//        LOG.info("---------------------------------wxresult="+wxresult);
//
//        return result.toJson();
    }
}
